import 'dart:convert';
import 'dart:typed_data';
import 'package:dio/dio.dart' as dioLibary;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart' as getLibary;
import 'package:get/get_core/src/get_main.dart';

import 'dart:async';
import '../views/login/LoginVC.dart';
import 'DialogUtil.dart';
import 'StorageUtil.dart';
import 'ToastUtil.dart';



class BaseRequest {
   static dioLibary.Dio? dio;
   static BuildContext? viewContext;
  /// default options
  static const String API_PREFIX = 'http://119.91.29.192:8889/yuellyflow/';
 //  static const String API_PREFIX = 'http://127.0.0.1:8080/yuellyflow/';
  static const int CONNECT_TIMEOUT = 10000;
  static const int RECEIVE_TIMEOUT = 3000;

  /// http request methods
  static const String GET = 'get';
  static const String POST = 'post';
  static const String PUT = 'put';
  static const String PATCH = 'patch';
  static const String DELETE = 'delete';

  static String errorStr='request_error'.tr;

  ///Get请求测试
  static void getHttp() async {
    try {
      dioLibary.Response response = await dioLibary.Dio().get("http://www.baidu.com");
      print("response$response");
    } catch (e) {
      print(e);
    }
  }

  ///Post请求测试
  static void postHttp<T>(
      String url, {
        parameters,
        required bool canTip,required BuildContext context,
        required Function(Map<String, dynamic> t) onSuccess,
        required Function(String error) onError,
      }) async {
      viewContext=context;

      url='${BaseRequest.API_PREFIX}$url';
    ///定义请求参数
    parameters = parameters ?? {};

    String? language=getLibary.Get.locale?.languageCode;
    String ll="en";
    if(language!=null&&language=='zh'){
      parameters['language']='cn';
      ll="cn";
    }else{
      parameters['language']='en';
    }
      debugPrint(url);
    //参数处理
    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    debugPrint(parameters.toString());
    try {
      dioLibary.Response? response;
      dioLibary.Dio? dio = createInstance();
      //dio?.options.headers.addAll({"language":ll});
      print('请求头: ' + dio!.options.headers.toString());

      //dio?.options.contentType="application/json";
      dio?.options.headers["language"]=ll;
      dio?.options.headers["Access-Control-Allow-Origin"]="*";
      dio?.options.headers["Access-Control-Allow-Headers"]="X-Requested-With,language";
      dio?.options.headers["Access-Control-Allow-Methods"]="PUT,POST,GET,DELETE,OPTIONS";
      dio?.options.headers["Content-Type"]="application/json";
      var userModel=StorageUtil.getToken();
      if(userModel!=null){
        dio?.options.headers["token"]=userModel;
      }
      var userId=StorageUtil.getUserId();
      if(userId!=null){
        dio?.options.headers["userId"]=userId;
      }
      if(canTip){
        goshowdialog();
      }
      response = await dio?.post(url, data: parameters);
      var string=response.toString();
      debugPrint("===响应数据$string");

      if(canTip){
        goHideDialog();
      }
      //登录问题。去登录
      if (response?.statusCode == 401) {
        onError('网络不给力，请稍后重试');
        ToastUtil.showToast('网络不给力，请稍后重试');
        StorageUtil.saveToken("");
        Get.to(const LoginVC());
        return;
      }

      var data=jsonDecode(string);
      if (response?.statusCode == 200) {
        if (onSuccess != null) {
          onSuccess(data);
        }
      } else {
        if(canTip){
          ToastUtil.showToast(data["message"]);
        }
        onError('网络不给力，请稍后重试');

      }

    } catch (e,stackTrace) {
      goHideDialog();
      if(canTip){
        ToastUtil.showToast(errorStr);
      }
      print('异常详情: $e');
      print('堆栈跟踪: $stackTrace');

  //    print('请求出错：' + e.toString());
      onError(errorStr);
    }
  }

   ///Post请求测试
   static void putHttp<T>(
       String url, {
         parameters,
         required bool canTip,required BuildContext context,
         required Function(T t) onSuccess,
         required Function(String error) onError,
       }) async {
     viewContext=context;
     ///定义请求参数
     parameters = parameters ?? {};
     //参数处理
     parameters.forEach((key, value) {
       if (url.indexOf(key) != -1) {
         url = url.replaceAll(':$key', value.toString());
       }
     });

     try {
       dioLibary.Response? response;
       dioLibary.Dio? dio = createInstance();
       if(canTip){
         goshowdialog();
       }
       response = await dio?.put(url, data: parameters);
       var string=response.toString();
       debugPrint("响应数据$string");
       var data=jsonDecode(string);
       if(canTip){
         goHideDialog();
       }
       if (response?.statusCode == 200) {
         if (onSuccess != null) {
           onSuccess(data);
         }
       } else {
         if(canTip){
           ToastUtil.showToast(data["message"]);
         }
         onError(errorStr);

       }

     } catch (e) {
       if(canTip){
         goHideDialog();
         ToastUtil.showToast(errorStr);
       }
       e.printError();
       onError(errorStr);
     }
   }

  /// request method
  //url 请求链接
  //parameters 请求参数
  //metthod 请求方式
  //onSuccess 成功回调
  //onError 失败回调
  static Future<Map<String, dynamic>> request<T>(String url,
      {parameters,
        method,
        required bool canTip,required BuildContext context,
        required Function(Map<String, dynamic> t) onSuccess,
        required Function(String error) onError}) async {
    parameters = parameters ?? {};
    method = method ?? 'GET';
    viewContext=context;
    /// 请求处理
    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    /// 打印:请求地址-请求方式-请求参数
    print('请求地址：【' + method + '  ' + url + '】');
    print('请求参数：' + parameters.toString());

    dioLibary.Dio? dio = createInstance();
    if(canTip){
      goshowdialog();
    }
    //请求结果
    Map<String, dynamic> result={};
    try {
      dioLibary.Response? response = await dio?.request(url,
          data: parameters, options: dioLibary.Options(method: method));
      String str=response.toString();
      debugPrint("响应数据$str");
      Map<String, dynamic> data=jsonDecode(str);

      if(canTip){
        goHideDialog();
      }
      result = data;
      if (response?.statusCode == 200) {
        if (onSuccess != null) {
          onSuccess(result);
        }
      } else {
        if(canTip){
          ToastUtil.showToast(data["message"]);
        }
        onError(errorStr);
      }

    } on dioLibary.DioError catch (e) {
      if(canTip){
        goHideDialog();
        ToastUtil.showToast(errorStr);
      }
      print('请求出错：' + e.toString());
      onError(errorStr);
    }

    return result;
  }



   /// request method
   //url 请求链接
   //parameters 请求参数
   //metthod 请求方式
   //onSuccess 成功回调
   //onError 失败回调
   static Future<Map<String, dynamic>> uploadImage<T>(
       {required String path,
         required bool canTip,required BuildContext context,
         required Function(Map<String, dynamic> t) onSuccess,
         required Function(String error) onError}) async {
     viewContext=context;
     dioLibary.Dio? dio = createInstance();
     if(canTip){
       goshowdialog();
     }
     //请求结果
     Map<String, dynamic> result={};
     String? language=getLibary.Get.locale?.languageCode;
     String ll="en";
     if(language!=null&&language=='zh'){
       ll="cn";
     }
     dio?.options.headers["language"]=ll;
     dio?.options.headers["Content-Type"]="multipart/form-data";
     try {
       dioLibary.FormData formData = dioLibary.FormData.fromMap({
          'file':await dioLibary.MultipartFile.fromFile(path)
       });
       dioLibary.Response? response = await dio?.request('${BaseRequest.API_PREFIX}file/upload2',
           data: formData,options: dioLibary.Options(method: 'POST'));
       String str=response.toString();
       debugPrint("响应数据$str");
       if(canTip){
         goHideDialog();
       }
       Map<String, dynamic> data=jsonDecode(str);
       result = data;
       if (response?.statusCode == 200) {
         if (onSuccess != null) {
           onSuccess(result);
         }
       } else {
         if(canTip){
           ToastUtil.showToast(data["message"]);
         }
         onError(errorStr);
       }

     } on dioLibary.DioError catch (e) {
       if(canTip){
         goHideDialog();
         ToastUtil.showToast(errorStr);
       }
       print('请求出错：' + e.toString());
       onError(errorStr);
     }

     return result;
   }


   static Future<Map<String, dynamic>> uploadToImportMaterial<T>(
       {required String path,required String partId,
         required bool canTip,required BuildContext context,
         required Function(Map<String, dynamic> t) onSuccess,
         required Function(String error) onError}) async {
     viewContext=context;
     dioLibary.Dio? dio = createInstance();
     if(canTip){
       goshowdialog();
     }
     //请求结果
     Map<String, dynamic> result={};
     String? language=getLibary.Get.locale?.languageCode;
     String ll="en";
     if(language!=null&&language=='zh'){
       ll="cn";
     }
     dio?.options.headers["language"]=ll;
     dio?.options.headers["Content-Type"]="multipart/form-data";
     try {
       dioLibary.FormData formData = dioLibary.FormData.fromMap({
         'file':await dioLibary.MultipartFile.fromFile(path),"partId":partId
       });
       dioLibary.Response? response = await dio?.request('${BaseRequest.API_PREFIX}price/importmaterial',
           data: formData,options: dioLibary.Options(method: 'POST'));
       String str=response.toString();
       debugPrint("响应数据$str");
       if(canTip){
         goHideDialog();
       }
       Map<String, dynamic> data=jsonDecode(str);
       result = data;
       if (response?.statusCode == 200) {
         if (onSuccess != null) {
           onSuccess(result);
         }
       } else {
         if(canTip){
           ToastUtil.showToast(data["message"]);
         }
         onError(errorStr);
       }

     } on dioLibary.DioError catch (e) {
       if(canTip){
         goHideDialog();
         ToastUtil.showToast(errorStr);
       }
       print('请求出错：' + e.toString());
       onError(errorStr);
     }

     return result;
   }

   static Future<Map<String, dynamic>> uploadImageByByte<T>(
       {required Uint8List listData,
         required bool canTip,required BuildContext context,
         required Function(Map<String, dynamic> t) onSuccess,
         required Function(String error) onError}) async {
     viewContext=context;
     dioLibary.Dio? dio = createInstance();
     if(canTip){
       goshowdialog();
     }
     //请求结果
     Map<String, dynamic> result={};
     String? language=getLibary.Get.locale?.languageCode;
     String ll="en";
     if(language!=null&&language=='zh'){
       ll="cn";
     }
     dio?.options.headers["language"]=ll;
     dio?.options.headers["Content-Type"]="multipart/form-data";
     try {
       dioLibary.FormData formData = dioLibary.FormData.fromMap({
         'file': dioLibary.MultipartFile.fromBytes(listData,filename: "sign.png")
       });

       dioLibary.Response? response = await dio?.request('${BaseRequest.API_PREFIX}file/upload2',
           data: formData,options: dioLibary.Options(method: 'POST'));
       String str=response.toString();
       debugPrint("响应数据$str");
       if(canTip){
         goHideDialog();
       }
       Map<String, dynamic> data=jsonDecode(str);
       result = data;
       if (response?.statusCode == 200) {
         if (onSuccess != null) {
           onSuccess(result);
         }
       } else {
         if(canTip){
           ToastUtil.showToast(data["message"]);
         }
         onError(errorStr);
       }

     } on dioLibary.DioError catch (e) {
       if(canTip){
         goHideDialog();
         ToastUtil.showToast(errorStr);
       }
       print('请求出错：' + e.toString());
       onError(errorStr);
     }

     return result;
   }


  /// 创建 dio 实例对象
  static dioLibary.Dio? createInstance() {
    String? language=getLibary.Get.locale?.languageCode;
    var ll="en";
    if(language!=null&&language=='zh'){
      ll="cn";
    }
    if (dio == null) {
      /// 全局属性：请求前缀、连接超时时间、响应超时时间
      var options = dioLibary.BaseOptions(
        connectTimeout: const Duration(milliseconds: 15000),
        receiveTimeout: const Duration(milliseconds: 15000),
        responseType: dioLibary.ResponseType.plain,

        validateStatus: (status) {
          // 不使用http状态码判断状态，使用AdapterInterceptor来处理（适用于标准REST风格）
          return true;
        },
        // baseUrl: API_PREFIX,
      );

      dio = dioLibary.Dio(options);
      //添加代理
      // dio?.httpClientAdapter = IOHttpClientAdapter()..onHttpClientCreate = (client) {
      //   // Config the client.
      //   client.findProxy = (uri) {
      //     // Forward all request to proxy "localhost:8888".
      //     return 'PROXY 192.168.1.46:8888';
      //   };
      //   // You can also create a new HttpClient for Dio instead of returning,
      //   // but a client must being returned here.
      //   return client;
      // };
    }

    return dio;
  }

  /// 清空 dio 对象
  static clear() {
    dio = null;
  }











  // late Dio dio;
  // late BuildContext viewContext;
  // String serverUrl="http://www.zhihuinonglin.com:80/";
  // BaseRequest() {
  //   dio = Dio();
  //   dio.options.headers = {
  //     'Content-Type': 'application/json;charset=UTF-8',
  //   };
  //
  //
  //
  //  }
  //
  // Future<Map<String, dynamic>> get(String path,
  //       bool canTip,BuildContext context,
  //     {required Map<String, dynamic> queryParameters}
  //
  //     ) async {
  //   try {
  //     path=serverUrl+path;
  //     viewContext=context;
  //     if(canTip){
  //       goshowdialog();
  //     }
  //     Response response = await dio.get(path, queryParameters: queryParameters);
  //     if(canTip){
  //       goHideDialog();
  //     }
  //     return json.decode(response.toString());
  //   } on DioError catch (e) {
  //     if(canTip){
  //       goHideDialog();
  //     }
  //     if (e.response != null) {
  //       // 请求成功，但是服务器返回错误信息
  //       return json.decode(e.response.toString());
  //     } else {
  //       // 请求失败
  //       debugPrint("异常了");
  //       throw Exception('网络异常，请稍后重试');
  //     }
  //   }
  // }
  // Future<Map<String, dynamic>> post(String path,
  //     bool canTip,BuildContext context,
  //     {required Map<String, dynamic> queryParameters}) async {
  //   try {
  //     viewContext=context;
  //     path=serverUrl+path;
  //     if(canTip){
  //       goshowdialog();
  //     }
  //     Response response = await dio.post(path, queryParameters: queryParameters);
  //     if(canTip){
  //       goHideDialog();
  //     }
  //     return json.decode(response.toString());
  //   } on DioError catch (e) {
  //     if(canTip){
  //       goHideDialog();
  //     }
  //     if (e.response != null) {
  //       // 请求成功，但是服务器返回错误信息
  //       return json.decode(e.response.toString());
  //     } else {
  //       // 请求失败
  //       throw Exception('网络异常，请稍后重试');
  //     }
  //   }
  // }

  static goshowdialog(){
    DialogUtil.showLoading("Loading...");
  }

 static goHideDialog(){
    DialogUtil.dismissLoading();
  }

  static bool chekResponse(var dic,bool showToast){
    int status=dic['status'];
    var data=dic['data'];
    if(status!=1){
      if(showToast){
        ToastUtil.showToast(data['errorMsg']);
      }
      return false;
    }

    return true;
  }

  static getDefaultJSon(){
    var parameters={};
    String? language=getLibary.Get.locale?.languageCode;
    String ll="en";
    if(language!=null&&language=='zh'){
      parameters['language']='cn';
      ll="cn";
    }else{
      parameters['language']='en';
    }



    return parameters;
  }
}

